package com.oceansoft.mobile.econsole.exam.controller;

import com.alibaba.fastjson.JSONArray;
import com.oceansoft.mobile.econsole.exam.entity.Attach;
import com.oceansoft.mobile.econsole.exam.entity.ExamTest;
import com.oceansoft.mobile.econsole.exam.entity.Option;
import com.oceansoft.mobile.econsole.exam.entity.Questions;
import com.oceansoft.mobile.econsole.exam.persistence.IExamMapper;
import com.oceansoft.mobile.econsole.exam.service.IExamService;
import com.oceansoft.mobile.econsole.exam.util.QuestionToDb;
import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import com.oceansoft.mobile.econsole.modules.base.entity.Pager;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.DELETE;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * Created by 祝亚 on 2016/8/16.
 */
@Controller
@RequestMapping("exam")
public class ExamController extends BaseController {

    @Resource
    private IExamService examService;
    @Resource
    private IExamMapper examMapper;

    /**
     * 进入考试信息管理首页（列表）
     *
     * @return String
     */
    @RequestMapping(value = "index")
    public String gotoIndex(Query query, Model model) {
        Pager<ExamTest> page = examService.findTestByCondition(query);
        model.addAttribute("query", query);
        model.addAttribute("pager", page);
        log(String.format("查看考试第%d页", query.getPageNum()));
        return "exam/test-list";
    }

    /**
     * 查看考试信息
     *
     * @return String
     */
    @RequestMapping(value = "view/{id}")
    public String newTest(@PathVariable int id, Model model) {
        ExamTest examTest = new ExamTest();
        if (id != -1) {
            examTest = examService.getExamTestById(id);
        }
        model.addAttribute("examTest", examTest);
        return "exam/test-new";
    }


    /**
     * 更新
     *
     * @param examTest
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "test/edit", method = POST)
    public Result editTest(ExamTest examTest, HttpServletRequest request) {
        try {
            Result r = examService.saveOrUpdateExamTest(examTest);
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "提交参数有误");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "test/delete/{id}", method = DELETE)
    public Result editTest(@PathVariable int id, HttpServletRequest request) {
        try {
            Result r = examService.deleteExamTest(id);
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "删除失败");
        }
    }

    /**
     * 导入题库页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "import/{id}")
    public String importQuetions(@PathVariable int id, Model model) {
        model.addAttribute("id", id);
        return "exam/question-import";
    }

    /**
     * 保存导入的题库
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "saveImportQuetions", method = POST)
    public Result saveImportQuetions(MultipartHttpServletRequest request) {
        MultipartFile requestFile =request.getFile("questions");
        int examid = Integer.parseInt(request.getParameter("id"));
        try {
            QuestionToDb questionToDb = new QuestionToDb(examMapper);
            questionToDb.importXLS("question_imp.xml", requestFile,examid);
        }catch (Exception e){
            e.printStackTrace();
        }
        Result result = new Result();
        result.setCallbackType(Result.CLOSECURRENT);
        result.setMsg("操作成功");
        return result;
    }

    //-----   题目管理开始---------//

    /**
     * 进入考试信息管理首页（列表）
     *
     * @return String
     */
    @RequestMapping(value = "question/index")
    public String gotoQuestions(Query query, Model model) {
        Pager<Questions> page = examService.findQuestionByCondition(query);
        model.addAttribute("query", query);
        model.addAttribute("pager", page);
        log(String.format("查看题目第%d页", query.getPageNum()));
        return "exam/question-list";
    }


    /**
     * 查看考试信息
     *
     * @return String
     */
    @RequestMapping(value = "question/view/{id}")
    public String newQuestion(@PathVariable int id, Model model) {
        Questions question = new Questions();
        List<Option> option = new ArrayList<Option>();
        if (id != -1) {
            question = examService.getQuestionById(id);
            option = examService.findOptionByQuestionId(id);
            List<Attach> questionAttach = examService.findAttachByQuestionId(id, "1");
            //List<Attach> optionAttach = examService.findAttachByQuestionId(id, "2");
            model.addAttribute("questionAttach", JSONArray.toJSONString(questionAttach));
        }
        List<ExamTest> examTests = examService.findAllTest();
        model.addAttribute("option", JSONArray.toJSONString(option));
        model.addAttribute("count", option.size());
        model.addAttribute("examTests", examTests);
        model.addAttribute("question", question);
        return "exam/question-new";
    }


    /**
     * 更新
     *
     * @param questions
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "question/new", method = POST)
    public Result newQuestions(Questions questions, MultipartHttpServletRequest request) {
        String q = "";
        try {
            Result r = examService.saveQuestions(questions, request);
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "提交参数有误");
        }
    }
//    /**
//     *删除
//     * @param id
//     * @param request
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "test/delete/{id}", method = POST)
//    public Result editTest(@PathVariable int id, HttpServletRequest request) {
//        try {
//            Result r =  examService.deleteExamTest(id);
//            return  r;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(Result.FAILURE, "删除失败");
//        }
//    }

}
